import 'package:flutter/material.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import '../Tools/ToolsLocalStorage.dart'; // 导入本地存储工具
import '../widgets/AppColors.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: LoginPage(),
    );
  }
}

class LoginPage extends StatefulWidget {
  const LoginPage({super.key});
  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final _formKey = GlobalKey<FormState>();
  late String _email = '', _password = '';
  bool browseOn = false; // Add this line
  bool _isChecked = false; // Add this line to track checkbox state
  get controller => null;
  final NetworkService _networkService = NetworkService();

  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      // Add WillPopScope to prevent back navigation
      onWillPop: () async => false, // Disable back button
      child: Scaffold(
        backgroundColor: AppColors.backgroundColor,
        body: Stack(
          children: [
            Positioned(
              top: 0,
              left: 0,
              right: 0,
              child: Image.asset(
                'assets/images/login/login_home_bg.png',
                fit: BoxFit.cover,
                height: 200,
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 130, left: 20),
              child: Column(
                children: [
                  TDText(
                    'WISave',
                    textColor: AppColors.textPrimary,
                    font: Font(
                        size: 22, lineHeight: 14, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 150, left: 20),
              child: Column(
                children: [
                  TDText(
                    '中冶南方智能加热炉系统',
                    textColor: AppColors.textPrimary,
                    font: Font(
                        size: 22, lineHeight: 44, fontWeight: FontWeight.bold),
                  ),
                ],
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 230),
              child: Container(
                margin: const EdgeInsets.symmetric(horizontal: 0),
                decoration: BoxDecoration(
                  color: AppColors.backgroundColor,
                  borderRadius: BorderRadius.circular(16),
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 10,
                      offset: const Offset(0, 5),
                    ),
                  ],
                ),
                child: SingleChildScrollView(
                  physics:
                      const NeverScrollableScrollPhysics(), // 禁用GridView的滚动
                  child: Padding(
                    padding: const EdgeInsets.all(20),
                    child: Column(
                      children: [
                        Container(
                          alignment: Alignment.centerLeft,
                          margin: const EdgeInsets.all(15),
                          child: TDText(
                            '用户名/手机号码',
                            textColor: AppColors.textPrimary,
                            font: TDTheme.of(context).fontMarkLarge,
                          ),
                        ),
                        TDInput(
                          type: TDInputType.normal,
                          controller: controller,
                          textStyle: TextStyle(color: AppColors.textPrimary),
                          leftIcon: Image.asset(AppColors.isDarkMode
                              ? 'assets/images/login/user_b.png'
                              : 'assets/images/login/user.png'),
                          hintText: '请输入用户名/手机号',
                          hintTextStyle:
                              TextStyle(color: AppColors.textPrimary),
                          backgroundColor: AppColors.backgroundColor,
                          needClear: false,
                          onChanged: (value) {
                            setState(() {
                              _email = value;
                              print(_email);
                            });
                          },
                        ),
                        Container(
                          alignment: Alignment.centerLeft,
                          margin: const EdgeInsets.all(15),
                          child: TDText(
                            '密码',
                            textColor: AppColors.textPrimary,
                            font: TDTheme.of(context).fontMarkLarge,
                          ),
                        ),
                        TDInput(
                          type: TDInputType.normal,
                          controller: controller,
                          obscureText: !browseOn,
                          textStyle: TextStyle(color: AppColors.textPrimary),
                          leftIcon: Image.asset(AppColors.isDarkMode
                              ? 'assets/images/login/password_b.png'
                              : 'assets/images/login/password.png'),
                          hintText: '请输入您的密码',
                          hintTextStyle:
                              TextStyle(color: AppColors.textPrimary),
                          backgroundColor: AppColors.backgroundColor,
                          onChanged: (value) {
                            setState(() {
                              _password = value;
                              print(_password);
                            });
                          },
                          rightBtn: browseOn
                              ? Icon(
                                  TDIcons.browse,
                                  color: TDTheme.of(context).fontGyColor3,
                                )
                              : Icon(
                                  TDIcons.browse_off,
                                  color: TDTheme.of(context).fontGyColor3,
                                ),
                          onBtnTap: () {
                            setState(() {
                              browseOn = !browseOn;
                            });
                          },
                          needClear: false,
                        ),
                        Container(
                          alignment: Alignment.centerLeft,
                          margin: const EdgeInsets.all(15),
                          child: TDText('用短信验证码登录',
                              textColor: AppColors.textPrimary,
                              font: Font(size: 13, lineHeight: 20)),
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: 30),
                          child: TextButton(
                              onPressed: () async {
                                if (_email.isEmpty) {
                                  TDToast.showText('请输入用户名/手机号',
                                      context: context);
                                  return;
                                }
                                if (_password.isEmpty) {
                                  TDToast.showText('请输入您的密码', context: context);
                                  return;
                                }
                                if (!_isChecked) {
                                  TDToast.showText('请先勾选服务协议和隐私政策',
                                      context: context);
                                  return;
                                }
                                print('=============== $_email');
                                print('=============== $_password');
                                try {
                                  final response = await _networkService.post(
                                    '/login',
                                    data: {
                                      'username': _email, //'admin', //
                                      'password': _password, //'ldkj123.', //,
                                    },
                                  );
                                  TDToast.showSuccess('登录成功',
                                      direction: IconTextDirection.vertical,
                                      context: context);
                                  print(response.data['user']);
                                  print(response.data['userDefaultDept']);
                                  print(response.data['token']);
                                  LocalStorage.setstr(
                                      'childDeptName',
                                      response.data['userDefaultDept']
                                          ['childDeptName']);
                                  LocalStorage.setstr(
                                      'deptName',
                                      response.data['userDefaultDept']
                                          ['deptName']);
                                  LocalStorage.setstr(
                                      'deptId',
                                      response.data['userDefaultDept']['deptId']
                                          .toString());
                                  LocalStorage.setstr(
                                      'token', response.data['token']);
                                  LocalStorage.setJson(
                                      'user', response.data['user']);
                                  final token =
                                      await LocalStorage.getstr('token');

                                  final user =
                                      await LocalStorage.getJson('user');
                                  print('token: $token');
                                  print('user: $user');
                                  Navigator.pop(context);
                                } catch (e) {
                                  // print('Error: $e');
                                  // TDToast.showText('账号或密码错误', context: context);
                                  // TDToast.showText('错误: $e', context: context);
                                }
                              },
                              style: TextButton.styleFrom(
                                padding: EdgeInsets.zero,
                                backgroundColor: Colors.transparent,
                                shadowColor: Colors.transparent,
                              ),
                              child: Container(
                                width: MediaQuery.of(context).size.width - 40,
                                height: 60,
                                decoration: BoxDecoration(
                                  image: const DecorationImage(
                                    image: AssetImage(
                                        'assets/images/login/login_bg.png'), // Replace with your image asset
                                    fit: BoxFit.fill,
                                  ),
                                  borderRadius: BorderRadius.circular(10),
                                ),
                                child: const Center(
                                  child: Text(
                                    '登录',
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 18,
                                    ),
                                  ),
                                ),
                              )),
                        ),
                        Container(
                          margin: const EdgeInsets.only(top: 150),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              GestureDetector(
                                onTap: () {
                                  setState(() {
                                    _isChecked = !_isChecked;
                                  });
                                },
                                child: Image.asset(
                                  _isChecked
                                      ? 'assets/images/login/icon_select.png'
                                      : 'assets/images/login/icon_unselect.png',
                                  width: 24,
                                  height: 24,
                                ),
                              ),
                              const SizedBox(
                                  width:
                                      4), // Add some space between the image and text
                              TDText(
                                '我已阅读、理解并同意',
                                textColor: AppColors.textPrimary,
                                font: Font(size: 14, lineHeight: 22),
                              ),
                              Container(
                                color: Colors.transparent,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children:
                                      _buildLinksWithType(TDLinkType.basic),
                                ),
                              ),
                              TDText(
                                '和',
                                textColor: AppColors.textPrimary,
                                font: Font(size: 14, lineHeight: 22),
                              ),
                              Container(
                                color: Colors.transparent,
                                child: Row(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children:
                                      _buildLinksWithType1(TDLinkType.basic),
                                ),
                              ),
                            ],
                          ),
                        ),
                        SizedBox(
                          height: MediaQuery.of(context).size.height - 400,
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

List<Widget> _buildLinksWithType(TDLinkType type) {
  return [
    TDLink(
      label: '服务协议',
      style: TDLinkStyle.defaultStyle,
      type: type,
      size: TDLinkSize.medium,
      color: AppColors.textPrimary,
    ),
  ];
}

List<Widget> _buildLinksWithType1(TDLinkType type) {
  return [
    TDLink(
      label: '隐私政策',
      style: TDLinkStyle.defaultStyle,
      type: type,
      size: TDLinkSize.medium,
      color: AppColors.textPrimary,
    ),
  ];
}
